package org.internna.expensetracker.model.support;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.internna.expensetracker.util.DateUtils;

public final class Interval {

	public static enum Intervals {
		MONTH_TO_DATE, YEAR_TO_DATE, ONE_YEAR, SIX_MONTHS, LAST_QUARTER, PREVIOUS_MONTH, PREVIOUS_YEAR;
	}

	private Date from, to;

	public Interval() {
		this(null, null);
	}

	public Interval(String intervals) {
		this(Intervals.valueOf(intervals.toUpperCase(Locale.ENGLISH)));
	}

	public Interval(Intervals intervals) {
		Calendar calendar = Calendar.getInstance();
		switch (intervals) {
			case MONTH_TO_DATE:
				this.to = calendar.getTime();
				DateUtils.getMonthStartDate(calendar);
				this.from = calendar.getTime();
				break;
			case YEAR_TO_DATE:
				this.to = calendar.getTime();
				DateUtils.getMonthStartDate(calendar);
				calendar.set(Calendar.MONTH, 0);
				this.from = calendar.getTime();
				break;
			case ONE_YEAR:
				this.to = calendar.getTime();
				DateUtils.getMonthStartDate(calendar);
				calendar.add(Calendar.MONTH, -11);
				this.from = calendar.getTime();
				break;
			case SIX_MONTHS:
				this.to = calendar.getTime();
				DateUtils.getMonthStartDate(calendar);
				calendar.add(Calendar.MONTH, -6);
				this.from = calendar.getTime();
				break;
			case LAST_QUARTER:
				this.to = calendar.getTime();
				calendar.add(Calendar.MONTH, -3);
				this.from = calendar.getTime();
				break;
			case PREVIOUS_MONTH:
				calendar.add(Calendar.MONTH, -1);
				DateUtils.getMonthEndDate(calendar);
				this.to = calendar.getTime();
				DateUtils.getMonthStartDate(calendar);
				this.from = calendar.getTime();
				break;
			default:
				calendar.add(Calendar.YEAR, -1);
				calendar.set(Calendar.MONTH, 11);
				calendar.set(Calendar.DAY_OF_MONTH, 31);
				DateUtils.end(calendar);
				this.to = calendar.getTime();
				DateUtils.getMonthStartDate(calendar);
				calendar.set(Calendar.MONTH, 0);
				this.from = calendar.getTime();
				break;
		}
	}

	public Interval(Date from) {
		this.to = new Date();
		this.from = from == null ? new Date(0): from;
	}

	public Interval(Date from, Date to) {
		this.from = from == null ? new Date(0): from;
		this.to = to == null ? new Date() : to;
	}

	public Date getFrom() {
		return from;
	}

	public Date getTo() {
		return to;
	}

	public int getNumberOfMonths() {
		return DateUtils.getMonths(from, to);
	}

}
